package com.seckill.controller;

import com.seckill.domain.MiaoshaUser;
import com.seckill.redis.GoodsKey;
import com.seckill.redis.RedisService;
import com.seckill.result.Result;
import com.seckill.service.GoodsService;
import com.seckill.service.MiaoshaUserService;
import com.seckill.vo.GoodsDetailVo;
import com.seckill.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author yangjunwei
 * @date 2021/10/31 6:22 下午
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    MiaoshaUserService miaoshaUserService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    RedisService redisService;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 登陆成功之后，跳转到商品列表页面
     */
    @RequestMapping("/to_list")
    @ResponseBody
    public String toGoodsList(HttpServletRequest request, HttpServletResponse response,
        Model model, MiaoshaUser user) {
        model.addAttribute("user", user);
        //取缓存
        String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
        if (StringUtils.isNotBlank(html)) {
            return html;
        }
        List<GoodsVo> goodsList = goodsService.getGoodsList();
        model.addAttribute("goodsList", goodsList);
        SpringWebContext ctx = new SpringWebContext(request, response, request.getServletContext(),
            request.getLocale(), model.asMap(), applicationContext);
        //手动渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if (StringUtils.isNotBlank(html)) {
            //添加缓存，过期时间60s
            redisService.set(GoodsKey.getGoodsList, "", html);
        }
        return html;
    }

    /**
     * 前后端分离 后端只返回数据
     */
    @GetMapping("/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVo> goodsDetail(MiaoshaUser user, @PathVariable("goodsId") long goodsId) {

        GoodsVo goodsVo = goodsService.selectGoodsVoById(goodsId);
        long startDate = goodsVo.getStartDate().getTime();
        long endDate = goodsVo.getEndDate().getTime();
        long now = System.currentTimeMillis();

        //秒杀状态；（0：未开始；1：进行中；2：已结束）
        int miaoshaStatus;
        //剩余时间
        int remainSeconds;

        if (now < startDate) {
            //秒杀未开始
            miaoshaStatus = 0;
            remainSeconds = (int) (startDate - now) / 1000;
        } else if (now > endDate) {
            //秒杀已结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        goodsDetailVo.setMiaoshaStatus(miaoshaStatus);
        goodsDetailVo.setRemainSeconds(remainSeconds);
        goodsDetailVo.setGoods(goodsVo);
        goodsDetailVo.setUser(user);
        return Result.success(goodsDetailVo);
    }

    /**
     * URL缓存 相当于页面缓存，每个商品详情对应一个缓存，相当于一个URL对应一个缓存 注意：前后端未分离；最终不使用
     */
    @Deprecated
    @RequestMapping("/to_detail/{goodsId}")
    @ResponseBody
    public String toGoodsDetail(HttpServletRequest request, HttpServletResponse response,
        Model model, MiaoshaUser miaoshaUser,
        @PathVariable("goodsId") long goodsId) {
        //缓存中取前端页面
        String html = redisService.get(GoodsKey.getGoodsDetail, GoodsKey.getGoodsKey(goodsId), String.class);
        if (StringUtils.isNotBlank(html)) {
            return html;
        }

        model.addAttribute("user", miaoshaUser);
        GoodsVo goodsVo = goodsService.selectGoodsVoById(goodsId);
        model.addAttribute("goods", goodsVo);

        long startDate = goodsVo.getStartDate().getTime();
        long endDate = goodsVo.getEndDate().getTime();
        long now = System.currentTimeMillis();

        //秒杀状态；（0：未开始；1：进行中；2：已结束）
        int miaoshaStatus;
        int remainSeconds;

        if (now < startDate) {
            miaoshaStatus = 0;
            remainSeconds = (int) (startDate - now) / 1000;
        } else if (now > endDate) {
            miaoshaStatus = 2;
            remainSeconds = -1;
        } else {
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("miaoshaStatus", miaoshaStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        //手动渲染
        SpringWebContext ctx = new SpringWebContext(request, response, request.getServletContext(),
            request.getLocale(), model.asMap(), applicationContext);
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
        if (StringUtils.isNotBlank(html)) {
            //添加缓存
            redisService.set(GoodsKey.getGoodsDetail, GoodsKey.getGoodsKey(goodsId), String.class);
        }
        return html;
    }

//    /**
//     * 登陆成功之后，跳转到商品列表页面
//     */
//    @RequestMapping("/to_list")
//    public String toGoodsList(Model model, MiaoshaUser user) {
//        model.addAttribute("user", user);
//        List<GoodsVo> goodsList = goodsService.getGoodsList();
//        model.addAttribute("goodsList", goodsList);
//        return "goods_list";
//    }
//
//    @RequestMapping("/to_detail/{goodsId}")
//    public String toGoodsDetail(Model model, MiaoshaUser miaoshaUser,
//                                @PathVariable("goodsId") long goodsId) {
//        model.addAttribute("user", miaoshaUser);
//        GoodsVo goodsVo = goodsService.selectGoodsVoById(goodsId);
//        model.addAttribute("goods", goodsVo);
//
//        long startDate = goodsVo.getStartDate().getTime();
//        long endDate = goodsVo.getEndDate().getTime();
//        long now = System.currentTimeMillis();
//
//        //秒杀状态；（0：未开始；1：进行中；2：已结束）
//        int miaoshaStatus = 0;
//        int remainSeconds = 0;
//
//        if (now < startDate) {
//            miaoshaStatus = 0;
//            remainSeconds = (int) (startDate - now) / 1000;
//        } else if (now > endDate) {
//            miaoshaStatus = 2;
//            remainSeconds = -1;
//        } else {
//            miaoshaStatus = 1;
//            remainSeconds = 0;
//        }
//        model.addAttribute("miaoshaStatus", miaoshaStatus);
//        model.addAttribute("remainSeconds", remainSeconds);
//        return "goods_detail";
//    }


}
